package com.hxzy.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.WaimaiException;
import com.hxzy.controller.admin.vo.mapstruct.EmployeeConvert;
import com.hxzy.controller.admin.vo.req.EmployeeReq;
import com.hxzy.controller.admin.vo.req.LoginReq;
import com.hxzy.controller.admin.vo.resp.AdminLoginResp;
import com.hxzy.controller.admin.vo.resp.EmployeeResp;
import com.hxzy.entity.Employee;
import com.hxzy.service.EmployeeService;
import com.hxzy.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
* @author tonneyyy
* @description 针对表【employee(后台管理员表)】的数据库操作Service实现
* @createDate 2023-06-10 09:55:41
*/
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee>
    implements EmployeeService{

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 分页查询
     * @param req
     * @return
     */
    @Override
    public PageInfo<EmployeeResp> search(EmployeeReq req) {
        return PageHelper.startPage(req.getPage(),req.getSize())
                .doSelectPageInfo(()->{
                    employeeMapper.search(req);
                });
    }

    @Override
    public AdminLoginResp login(LoginReq req) {
        //mybatis-plus语法来写 支持 Lambda 形式调用：通过 Lambda 表达式，方便的编写各类查询条件，无需再担心字段写错
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getLoginName, req.getUsername());

        //查询
        Employee db = this.employeeMapper.selectOne(queryWrapper);
        if(Objects.isNull(db)){
            throw new WaimaiException(AckCode.LOGIN_ACCOUNT_PASSWORD_ERROR);
        }

        //判断密码  hutool工具
        boolean correct= BCrypt.checkpw(req.getPassword(),  db.getLoginPwd());
        if(!correct){
            throw new WaimaiException(AckCode.LOGIN_ACCOUNT_PASSWORD_ERROR);
        }
        //判断 状态
        if(db.getStatus()==1){
            throw new WaimaiException(AckCode.DEVICE_BANNED);
        }
        //大家额外的功能
        //如果登录次数在5分钟之内错误了3次，账户锁定10分钟，10分钟以后自动解锁(redis来实现)

        //转换
        AdminLoginResp adminLoginResp = EmployeeConvert.INSTANCE.convertResp(db);
        adminLoginResp.setAccountType(1);
        return adminLoginResp;
    }
}




